import operator
import pandas as pd
from pandas import DataFrame
from app01 import models

end_dic = []
temp_long = []
# 排序
processed_data = {}
# 最后排序
end_processed_data = {}
end_end_data = {'姓名': [], '考勤号': []}

new_is_night = {'is_night': False}
is_night = False


def get_data(path):
    """
    获取原始数据
    :param path:
    :return:
    """

    df = pd.read_excel(path)
    # 数据清洗，kong替换成0  astype：类型转换
    df.fillna(0, inplace=True)
    data_list = df.values.tolist()

    return data_list


def get_classes_data(data_list):
    """"
    数据转换
    """
    # 存储临时数据
    temp_data_dic = {}
    for item in data_list:

        # 姓名
        name = item[0]
        # 考勤号
        Attendance_number = item[1]
        # 打卡时间
        Clock_in_time = item[2]

        ymd = Clock_in_time.split()[0].strip()
        hms = Clock_in_time.split()[1].strip()
        # print(department)
        # print(name)
        # print(Attendance_number)
        # print(ymd)
        # print(hms)
        # print(Clock_in_time)

        # 把打卡数据都放进一个字典里面
        if ymd in temp_data_dic:
            # 拿到内部名字字典
            if name in temp_data_dic[ymd]:
                temp_data_dic[ymd][name]['classes'].append(hms)
            else:
                temp_data_dic[ymd][name] = {
                    'name': name, 'Attendance_number': Attendance_number,
                    'Clock_in_time': Clock_in_time, 'ymd': ymd, 'hms': hms, 'classes': [hms]
                }
        else:
            temp_data_dic[ymd] = {

                name: {
                    'name': name, 'Attendance_number': Attendance_number,
                    'Clock_in_time': Clock_in_time, 'ymd': ymd, 'hms': hms, 'classes': [hms]
                }

            }

            # time_slot(ymd, hms, temp_data_dic, Clock_in_time)
            # print('>>>>>>>>>>>>>')
    return temp_data_dic


# 跨业 中 一个 0

def is_sure_one(end_hms_timer):
    """
    第一次打卡，签到判断
    :param string:
    :return:
    """

    if 6 * 60 * 60 <= end_hms_timer <= 9 * 60 * 60:
        return '早'

    elif 13 * 60 * 60 <= end_hms_timer <= 16 * 60 * 60 or 0 * 60 * 60 <= end_hms_timer <= 3 * 60 * 60:
        return '中'

    elif 6 * 60 * 60 <= end_hms_timer <= 11 * 60 * 60:
        return '晚'
    else:
        return '缺卡'


def is_sure_tow(string, end_hms_timer, name, classes, ymd):
    """
    第二次打卡,签退判断
    :param string:
    :return:
    """
    if string == '早':
        """
        早：李学平 2023/4/25 ['7:22:07', '16:48:03']
        晚：霍晓鹏 2023/5/2 ['7:57:12', '23:12:54']
        晚：霍晓鹏 2023/5/2 ['23:12:54', '23:12:54']
        中：马儒山 2023/5/7 ['0:07:58', '17:58:03']
        中：马儒山 2023/5/7 ['14:07:58', '23:58:03']

        """
        if 14 * 60 * 60 <= end_hms_timer <= 20 * 60 * 60:
            return '早'
        else:
            if 22 * 60 * 60 <= end_hms_timer <= 24 * 60 * 60:
                return '晚'
            return '缺卡'

    elif string == '中':
        # 因为两次下班都是过夜签到
        if 22 * 60 * 60 <= end_hms_timer <= 24 * 60 * 60:
            return '中'
        elif 13 * 60 * 60 <= end_hms_timer <= 16 * 60 * 60:
            # 处理两次都是 13-16的鱼龙混杂
            Clock_time = ymd + ' ' + classes
            ret = models.Excel_data.objects.filter(work_name=name, Clock_time=Clock_time).last()
            next_ret = models.Excel_data.objects.filter(pk=int(ret.pk + 1)).first()
            Clock_time = next_ret.Clock_time  # 2023/5/22 7:18:03
            # 下一个时间进行判断，如果是在0-3 那么为打卡了，否则就是缺卡
            next_hms_h = int(Clock_time.split(' ')[-1].split(':')[0])
            if 0 <= next_hms_h <= 3:
                return '中'
            return '缺卡'
        return '缺卡'

    elif string == '夜':
        if 22 * 60 * 60 <= end_hms_timer <= 24 * 60 * 60:
            return '中'
        return '缺卡'
    else:
        return '缺卡'


def data_to_classes(name, ymd, classes):
    """
    日期转打卡
    :param name:
    :param ymd:
    :param classes:
    :return:
    """

    # print(name)
    # print(ymd)
    # print(classes)
    # print('>>>>>>>>>>>>>>>>>>>>>')
    """
    李学平
    2023/4/25
    ['7:22:07', '8:24:56', '9:43:00', '11:54:52', '16:48:03']
    2023/4/25 7:22:07

    'Clock_in_time': '2023/5/25 6:24:19'
    
    # 早班 ['2023/4/25 7:22:07', '2023/4/25 16:48:03']
    # 中班 
    """
    # 最终班次
    # end_classes = ''
    # 上下班时间
    classes_list = []
    # 进行处理，只要上班时间，下班时间
    # classes_list.append(ymd + ' ' + classes[0])
    # classes_list.append(ymd + ' ' + classes[-1])
    classes_list.append(classes[0])
    classes_list.append(classes[-1])
    # print(name, ymd, classes_list)
    # 进行单个拦截，如果是单个的话，单独判断，只会出现在跨业的中 夜上面
    if classes_list[0] == classes_list[-1]:
        """
        李学平 2023/5/16 ['7:19:12', '7:19:12']  真正的缺卡
        李学平 2023/5/15 ['17:25:29', '17:25:29']
        牛金亮 2023/5/20 ['7:10:02', '7:10:02']
        张龙 2023/5/24 ['17:53:37', '17:53:37']
        """
        h_0 = int(classes_list[0].split(':')[0].strip())
        m_0 = int(classes_list[0].split(':')[1].strip())
        s_0 = int(classes_list[0].split(':')[2].strip())
        end_hms_timer_night_0 = h_0 * 60 * 60 + m_0 * 60 + s_0
        # 中班换夜不可能出现就一个，
        if 0 * 60 * 60 <= end_hms_timer_night_0 <= 3 * 60 * 60:
            return '缺卡'
        if 22 * 60 * 60 <= end_hms_timer_night_0 <= 24 * 60 * 60:
            return '晚'
        if 13 * 60 * 60 <= end_hms_timer_night_0 <= 16 * 60 * 60:
            Clock_time = ymd + ' ' + classes_list[0]
            ret = models.Excel_data.objects.filter(work_name=name, Clock_time=Clock_time).last()
            next_ret = models.Excel_data.objects.filter(pk=int(ret.pk + 1)).first()
            Clock_time = next_ret.Clock_time  # 2023/5/22 7:18:03
            # 下一个时间进行判断，如果是在0-3 那么为打卡了，否则就是缺卡
            next_hms_h = int(Clock_time.split(' ')[-1].split(':')[0])
            if 0 <= next_hms_h <= 3:
                return '中'
            return '缺卡'
        return '缺卡'

    # 先确认两个不一致的
    # 进行数据切分
    h_1 = int(classes_list[0].split(':')[0].strip())
    m_1 = int(classes_list[0].split(':')[1].strip())
    s_1 = int(classes_list[0].split(':')[2].strip())
    end_hms_timer_night_1 = h_1 * 60 * 60 + m_1 * 60 + s_1

    # 第一次
    string_1 = is_sure_one(end_hms_timer_night_1)
    # 第二次判断
    h_2 = int(classes_list[-1].split(':')[0].strip())
    m_2 = int(classes_list[-1].split(':')[1].strip())
    s_2 = int(classes_list[-1].split(':')[2].strip())
    end_hms_timer_night_2 = h_2 * 60 * 60 + m_2 * 60 + s_2
    string_2 = is_sure_tow(string_1, end_hms_timer_night_2, name, classes_list[-1], ymd)
    return string_2

    # # 进行日期还原
    # for hms in classes_list:
    #     Clock_time = ymd + ' ' + hms
    #     ret_all = models.Excel_data.objects.filter(work_name=name).all()
    # 上一条数据
    # previous_ret = models.Excel_data.objects.filter(pk=int(ret.pk - 1)).first()
    # next_ret = models.Excel_data.objects.filter(pk=int(ret.pk + 1)).first()
    # if previous_ret:
    #     print('previous_ret---->', previous_ret.Clock_time)
    #
    # print('ret---->', ret.Clock_time)
    # if next_ret:
    #     print('next_ret---->', next_ret.Clock_time)
    # # 下一条数据
    # print('>>>>>')


def time_slot(data_dic=None):
    """
    数据处理
    :return:
    """

    temp_data_dic_2 = {}
    end_data = {}
    for item in data_dic.values():
        for end_item in item.values():
            # print(item)
            # print(end_item)
            # 最终返回  早 中 晚

            new_classes_list = data_to_classes(name=end_item['name'], ymd=end_item['ymd'], classes=end_item['classes'])

            # print(classes_list,'>>>>>')
            item[end_item['name']]['classes'] = new_classes_list
            # print(classes_list)
            temp_data_dic_2[end_item['ymd']] = item

            # print('>>>>>>结束>>>>>>>')
    # print(temp_data_dic_2)
    for k1, v1 in temp_data_dic_2.items():
        # k1:2023/5/24

        # v1:{'李学平': {'name': '李学平', 'department': '三交一号工作组', 'Attendance_number': '1001', 'Clock_in_time': '2023/5/26 7:33:55', 'ymd': '2023/5/26', 'hms': '7:33:55', 'classes': '早'},}
        # print(v1)
        # print(k1)
        for k2, v2 in v1.items():
            # print(k2)
            # print(v2)
            #     print('>>>>>>>>>>>')
            # print('------------------------')
            if k2 in end_data:
                end_data[k2][v2['ymd']] = {'Attendance_number': v2['Attendance_number'],
                                           'Clock_in_time': v2['Clock_in_time'],
                                           'hms': v2['hms'], 'classes': v2['classes']}
            else:
                end_data[k2] = {
                    v2['ymd']: {'Attendance_number': v2['Attendance_number'],
                                'Clock_in_time': v2['Clock_in_time'],
                                'hms': v2['hms'], 'classes': v2['classes']}}
    # print(end_data)
    return end_data


def write_excel(temp_data_dic_2, path, max_leng=0, max_dic={}):
    """
    数据写入
    :return:
    """
    # print(temp_data_dic_2)
    # 最大数据获取
    for x1, x2 in temp_data_dic_2.items():
        # print(len(x2))
        new_leng = len(x2)
        if new_leng > max_leng:
            max_leng = new_leng
            max_dic = {x1: x2}
            # max_dic = x2
    # 获取最大打卡长度的时间
    # for l in max_dic.keys():
    for l in max_dic.values():
        for q in l:
            temp_long.append(q)
    # print(temp_long, '>>>>>')

    # 数据构造
    for a1, a2 in temp_data_dic_2.items():
        temp_short = []
        if len(a2) < max_leng:
            # 如果小于，判断是否有，没有直接添加值
            for i in temp_long:
                ret = a2.get(list(a2.keys())[-1])
                if i not in a2:
                    a2[i] = {'Attendance_number': ret['Attendance_number'],
                             'Clock_in_time': '',
                             'hms': '', 'classes': '缺卡'}
            sort_key_dic_instance = dict(sorted(a2.items(), key=operator.itemgetter(0)))  # 按照key值升序
            processed_data[a1] = sort_key_dic_instance
            # print(processed_data)
        else:
            processed_data[a1] = a2

    # print(processed_data)
    # print(max_dic)
    # print(temp_long)

    # 数据最后清洗，排序
    for m in temp_long:
        # print(m)
        for i, k in processed_data.items():
            if i in end_processed_data:
                end_processed_data[i][m] = k[m]
            else:
                end_processed_data[i] = {
                    m: k[m]
                }
    # print(end_processed_data)
    """"""

    for key, value in end_processed_data.items():
        # print(key)
        for j2, k2 in value.items():
            # 构造年月
            ret = j2.split('/')
            ret.remove(ret[0])
            end_ret = '%s月%s日' % (ret[0], ret[1])
            # print(j2)
            if end_ret not in end_end_data:
                end_end_data[end_ret] = []
            if k2['Attendance_number'] not in end_end_data['考勤号']:
                end_end_data['考勤号'].append(k2['Attendance_number'])
            # print(k2)
            end_end_data[end_ret].append(k2['classes'])
        end_end_data['姓名'].append(key)
    # print(end_data)
    data = end_end_data
    # print(data)
    df = DataFrame(data)
    df.to_excel(path, index=False)
